#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define CONV(addr_ptr) ((struct sockaddr *)addr_ptr)
#define Retry_Count 5 // 重连次数

void Usage(const std::string &process)
{
    std::cout << "Usage: " << process << " server_ip server_port" << std::endl;
}

bool AccessService(std::string &serverip, uint16_t &serverport, int *cnt)
{
    bool ret = true;
    ssize_t m = 0;
    ssize_t n = 0;
    std::string inbuffer;
    char service_list[1024];
    // 1. 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        return false;
    }
    // 2. 填充本地网络信息
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr); // 字符串ip转化为网络序列4字节ip

    // 3. 主动建立连接
    n = connect(sockfd, CONV(&server), sizeof(server)); // 自动进行bind
    if (n < 0)
    {
        std::cerr << "connect error" << std::endl;
        ret = false;
        goto END;
        // TODO
    }
    *cnt = 1;
    // 读取服务列表
    m = read(sockfd, service_list, sizeof(service_list) - 1);
    if (m > 0)
    {
        service_list[m] = 0;
        std::cout << "服务器提供的服务列表是: " << service_list << std::endl;
    }
    // 4. 进行通信
    std::cout << "请你选择服务#  ";
    std::getline(std::cin, inbuffer);
    write(sockfd, inbuffer.c_str(), inbuffer.size());

    std::cout << "Enter> ";
    std::getline(std::cin, inbuffer);

    if (inbuffer == "quit")
        return true;
        
    n = write(sockfd, inbuffer.c_str(), inbuffer.size());
    if (n > 0)
    {
        char buffer[1024];
        m = read(sockfd, buffer, sizeof(buffer) - 1);
        if (m > 0)
        {
            buffer[m] = 0;
            std::cout << buffer << std::endl;
        }
        else if (m == 0)
        {
            return true;
        }
        else
        {
            ret = false;
            goto END;
        }
    }
    else
    {
        ret = false;
        goto END;
    }

END:
    close(sockfd);
    return ret;
}

// ./tcp_client server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    // 获取server的IP和port
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int cnt = 1;
    while (cnt <= Retry_Count)
    {
        bool result = AccessService(serverip, serverport, &cnt);
        if (result)
        {
            // 连接并访问成功
            break;
        }
        else
        {
            // 访问失败进行重连
            sleep(1);
            std::cout << "server offline, retrying..., count : " << cnt << std::endl;
            cnt++;
        }
    }
    if (cnt >= Retry_Count)
    {
        std::cout << "server offline" << std::endl;
    }
    return 0;
}